package com.my.socket.nio.v19;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Created by ZhongGang
 * at 2018/7/4 18:01
 */
public class Client {
    private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {

            try (Socket socket = new Socket()) {
                socket.connect(new InetSocketAddress("127.0.0.1", 9999));
                LOGGER.info("connect: {}", socket);

                OutputStream outputStream = socket.getOutputStream();
                IOUtils.write("I am Alex Zhong", outputStream, "UTF-8");
                socket.shutdownOutput();

                InputStream inputStream = socket.getInputStream();
                String response = IOUtils.toString(inputStream, "UTF-8");
                socket.shutdownInput();
                LOGGER.info("read: {}", response);
            }
        }
        LOGGER.info("it takes {} second(s)", (System.currentTimeMillis() - start) / 1000.00);
    }
}
